import React from 'react';
import {Form, Input, Button} from 'antd';

const FormItem = Form.Item;

const CustomizedForm = Form.create({
  onFieldsChange(props, changeFields) {
    props.onChange(changeFields);
  },

  mapPropsToFields(props) {
    return {
      username: Form.createFormField({
        ...props.username,
      }),
      password: Form.createFormField({
        ...props.password,
      }),
    };
  },

  onSubmit() {
    console.log(this)
  }
  // onValuesChange(_, values) {
  //   console.log(values);
  // }
})( (props) =>{
  const { getFieldDecorator, isFieldTouched, getFieldError, validateFields } = props.form;
  const userNameError = isFieldTouched('username') && getFieldError('username');
  const passwordError = isFieldTouched('password') && getFieldError('password');

  const handleSubmit = () => {
    validateFields((err, values)=>{
      if (!!!err) {
        console.log(values);
      }
    });
  };

  return (
    <Form layout="horizontal" onSubmit={handleSubmit}>
      <FormItem label="username"
        validateStatus={userNameError?'error':'success'}
        hasFeedback={userNameError?true:false}
        help={userNameError||''}
        style={{
          width: 360
        }}
      >
        {
          getFieldDecorator("username", {
            rules:[{
              required: true,
              message: '必填项'
            }]
          })(<Input type="text" autoComplete="off" placeholder="用户名"/>)
        }
      </FormItem>
      
      <FormItem label="password"
        validateStatus={passwordError?'error':'success'}
        hasFeedback={passwordError?true : false}
        help={passwordError||''}
        style={{
          width: 360
        }}
      >
        {
          getFieldDecorator("password", {
            rules:[
              {required: true, message: '必填项' },
              {min: 6, max: 14, message: '密码由6-14位字母或者数字组成'},
              {pattern: RegExp("^\\w+$","g"), message: '格式错误，密码由字母或者数字组成'}
            ]
          })(<Input type="password" autoComplete="off" placeholder="密码"/>)
        }
      </FormItem>

      <Button
        type="primary"
        htmlType="submit"
        disabled={!!userNameError||!!passwordError}
      >login</Button>
    </Form>
  );
} );

class ResetForm extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      fields: {
        username: {
          value: 'benjycui',
        },
        password: {
          value: '123456'
        }
      }
    }
  }

  handleFormChange = (changedFields) => {
    this.setState(({fields}) => ({
        fields: {...fields, ...changedFields}
      }))
  }



  render() {
    const fields = this.state.fields;
    return(
      <div>
        <CustomizedForm {...fields} onChange={(changedFields) => this.handleFormChange(changedFields)} />
        <pre>
          {JSON.stringify(fields, null, 2)}
        </pre>
      </div>
    )
  }
}

export default ResetForm;